"use strict";  // 使用严格模式的JS

import Vue from 'vue';
import axios from "axios";
import store from '../store'
import router from '../router'
import basepath from './base'
import { Message } from 'element-ui'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//配置参数
let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  //baseUrl: baseApi
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
  //headers:{Authorization: store.state.user.Token}
};

//创建一个 axios 对象
const _axios = axios.create(config);

//请求拦截器
_axios.interceptors.request.use(
  function (config) {

    config.url = basepath.apiUrl + config.url;
    // Do something before request is sent
    //附加 Token  jwt  票据认证
    config.headers = { Authorization: store.state.user.Token }
    // if(store.state.user.Token.length<1){
    //   router.push('/login');
    // }
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
//响应拦截器
_axios.interceptors.response.use(
  function (response) {
    //console.log('response: ', response);
    // Do something with response data

    return response;
  },
  function (error) {
    Message({
      message:error.request.responseText,
      type:'error'
    })
    console.log(error.request);
    if(error.request.status==401)
      {
        router.push('/login');
      }
    // Do something with response error
    return Promise.reject(error);
  }
);


Plugin.install = function (Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
